package org.hsieh.tr.explore.ui.console;

import java.io.IOException;
import java.io.PrintStream;

import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleFactory;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.console.MessageConsoleStream;
import org.hsieh.tr.explore.exception.ExceptionHandler;
import org.hsieh.tr.explore.ui.ResourceHandler;

public class TextResultConsole implements IConsoleFactory {
    public static final String ID = "TextConsole";
    private static MessageConsole console;

    public void openConsole() {
	showConsole();
    }

    public static void showConsole() {
	try {
	    if (console == null) {
		console = new MessageConsole("DB Text Result", ResourceHandler
			.getInstance().getImageDescriptor(
				"icons/db/look-n-feel-icon.png"));
		console.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_BLUE));
		console.setFont(JFaceResources.getFont("Calibri"));
	    }
	    IConsoleManager manager = ConsolePlugin.getDefault()
		    .getConsoleManager();
	    IConsole[] existing = manager.getConsoles();
	    boolean exists = false;
	    for (int i = 0; i < existing.length; i++) {
		if (console == existing[i])
		    exists = true;
	    }
	    if (!exists) {
		manager.addConsoles(new IConsole[] { console });
	    }
	    manager.showConsoleView(console);
	    MessageConsoleStream stream = console.newMessageStream();
	    stream.write("");
	    System.setOut(new PrintStream(stream));
	} catch (IOException e) {
	    ExceptionHandler.handle(e);
	}
    }

    public static void closeConsole() {
	IConsoleManager manager = ConsolePlugin.getDefault()
		.getConsoleManager();
	if (console != null) {
	    manager.removeConsoles(new IConsole[] { console });
	}
    }

    public static MessageConsole getConsole() {
	return console;
    }

    public static void console(String msg) {
	TextResultConsole.showConsole();
	MessageConsoleStream printer = TextResultConsole.console
		.newMessageStream();
	printer.println(msg);
    }
}
